package com.example.autopera.线程池;


import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author Code_lemon
 * @version 1.0.0
 * @description TODO
 * @date 2024/10/23 14:18
 * @title FixedThreadPoolExample
 */
public class FixedThreadPoolExample {

    private static final int fixedThread = 5;
    public static void main(String[] args) {
        // 创建线程池
        ExecutorService threadPool = Executors.newFixedThreadPool(fixedThread);
        // 干活
        try {

            for (int i = 1; i <= 10; i++) {
                // 真正创建线程池
                threadPool.execute(() -> {
                    System.out.println(Thread.currentThread().getName() + "办理业务");
                    try {
                        TimeUnit.SECONDS.sleep(new Random().nextInt(5));
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭线程池
            threadPool.shutdown();
        }
    }
}
